package com.nosite.batch.server.listener;

import com.nosite.batch.common.dao.UserInfoMapper;
import com.nosite.batch.common.po.UserInfo;
import com.nosite.batch.server.util.MailSenderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther: SunYuGuo
 * @Date: 2019/11/24 11:26
 * @Description:
 */
@Component
public class AutoCreateProductTaskletListener implements StepExecutionListener {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private MailSenderService mailSenderService;


    @Override
    public void beforeStep(StepExecution stepExecution) {

    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {

        ExitStatus exitStatus = stepExecution.getExitStatus();
        if (exitStatus.compareTo(ExitStatus.COMPLETED) != 0){
            //查询出所有系统管理员
            List<UserInfo> adminList = userInfoMapper.selectAllAdmin();
            //获取所有系统管理员的email
            Set<String> emailSet = adminList.stream().map(UserInfo::getEmail)
                    .filter((email)-> StringUtils.isNotBlank(email)).collect(Collectors.toSet());
            mailSenderService.setToSet(emailSet);
            mailSenderService.setCcSet(emailSet);
            mailSenderService.setSubject("电商后台批处理系统异常通知");
            mailSenderService.setTemplateName("sellAutoCreateProductEmailNotify.ftl");
            HashMap params = new HashMap();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            params.put("date",format.format(new Date()));
            params.put("errObject",stepExecution);
            mailSenderService.sendHtml(params);
        }
        return exitStatus;
    }
}
